using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DrawTools.Editor;
using DrawTools.Editor.CanvasFigures;
using DrawTools.Properties;

namespace DrawTools.Tools
{
  /// <summary>
  ///   Polygon tool
  /// </summary>
  public class PolylineTool : ObjectTool
  {
    private const int MIN_DISTANCE = 15 * 15;
    private int _lastX;
    private int _lastY;
    private CanvasPolyline _newPolygon;

    public PolylineTool()
    {
      Cursor = new Cursor(new MemoryStream(Resources.Pencil1));
    }

    /// <summary>
    ///   Left nouse button is pressed
    /// </summary>
    /// <param name="canvas"></param>
    /// <param name="e"></param>
    public override void OnMouseDown(IDrawingCanvas canvas, MouseEventArgs e)
    {
      // Create new polygon, add it to the list
      // and keep reference to it
      _newPolygon = new CanvasPolyline(e.X, e.Y, e.X + 1, e.Y + 1);
      AddNewObject(canvas, _newPolygon);
      _lastX = e.X;
      _lastY = e.Y;
    }

    /// <summary>
    ///   Mouse move - resize new polygon
    /// </summary>
    /// <param name="canvas"></param>
    /// <param name="e"></param>
    public override void OnMouseMove(IDrawingCanvas canvas, MouseEventArgs e)
    {
      canvas.SetCursor(Cursor);

      if (e.Button != MouseButtons.Left)
        return;

      if (_newPolygon == null)
        return; // precaution

      var point = new Point(e.X, e.Y);
      int distance = (e.X - _lastX) * (e.X - _lastX) + (e.Y - _lastY) * (e.Y - _lastY);

      if (distance < MIN_DISTANCE)
      {
        // Distance between last two points is less than minimum -
        // move last point
        _newPolygon.MoveHandleTo(point, _newPolygon.HandlesCount);
      }
      else
      {
        // Add new point
        _newPolygon.AddPoint(point);
        _lastX = e.X;
        _lastY = e.Y;
      }

      canvas.Refresh();
    }

    public override void OnMouseUp(IDrawingCanvas canvas, MouseEventArgs e)
    {
      _newPolygon = null;

      base.OnMouseUp(canvas, e);
    }
  }
}